<?php

namespace backend\modules\common\controllers;

use backend\models\ConfigCateDao;
use backend\models\ConfigValueDao;
use common\enums\AppEnum;
use common\enums\ConfigTypeEnum;
use common\enums\StatusEnum;
use common\helpers\ArrayHelper;
use common\helpers\ResultHelper;
use common\traits\Curd;
use Yii;
use backend\models\ConfigDao;
use backend\models\ConfigSearch;
use backend\controllers\BaseController;
use yii\db\ActiveQuery;
use yii\helpers\Json;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * ConfigController implements the CRUD actions for ConfigDao model.
 */
class ConfigController extends BaseController
{
    use Curd ;
    public $modelClass = ConfigDao::class ;

    /**
     * Lists all ConfigDao models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new ConfigSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->query
            ->andWhere(['app_id' => AppEnum::BACKEND])
            ->andWhere(['>=', 'status', StatusEnum::DISABLED]);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'cateDropDownList' => Yii::$app->services->configCate->getDropDown(AppEnum::BACKEND)
        ]);
    }

    public function actionAjaxEdit()
    {

        $id = Yii::$app->request->get('id');
        $model = $this->findModel($id);
        $model->app_id = AppEnum::BACKEND;

        // ajax 校验
        $this->activeFormValidate($model);
        if ($model->load(Yii::$app->request->post())) {
            return $model->save()
                ? $this->redirect(Yii::$app->request->referrer)
                : $this->message($this->getError($model), $this->redirect(Yii::$app->request->referrer), 'error');
        }

        return $this->renderAjax($this->action->id, [
            'model' => $model,
            'configTypeList' => ConfigTypeEnum::getMap(),
            'cateDropDownList' => Yii::$app->services->configCate->getDropDown(AppEnum::BACKEND)
        ]);
    }

    public function actionEditAll()
    {


          return $this->render('edit-all',['cates'=>Yii::$app->services->configCate->getItemsMergeForConfig(AppEnum::BACKEND)]);

    }

    /**
     * ajax批量更新数据
     *
     * @return array
     * @throws NotFoundHttpException
     * @throws \yii\base\InvalidConfigException
     */
    public function actionUpdateInfo()
    {
        $request = Yii::$app->request;
        if ($request->isAjax) {
            $post= $request->post('config', []);
           Yii::$app->services->config->updateAll(Yii::$app->id, $post);
            return ResultHelper::json(200, "修改成功");
        }

        throw new NotFoundHttpException('请求出错!');
    }

}
